package com.slipper.core.excel;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.NumberDataFormatterUtils;
import com.alibaba.excel.util.NumberUtils;
import com.alibaba.excel.util.StringUtils;

import java.math.BigDecimal;

public class StringNumberConverter implements Converter<String> {
    public StringNumberConverter() {
    }

    public Class<?> supportJavaTypeKey() {
        return String.class;
    }

    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.NUMBER;
    }

    public String convertToJavaData(
            ReadCellData<?> cellData,
            ExcelContentProperty contentProperty,
            GlobalConfiguration globalConfiguration) {
        if (contentProperty != null && contentProperty.getDateTimeFormatProperty() != null) {
            return DateUtils.format(
                    cellData.getNumberValue(),
                    contentProperty.getDateTimeFormatProperty().getUse1904windowing(),
                    getFormat(contentProperty.getDateTimeFormatProperty().getFormat()));
        } else if (contentProperty != null && contentProperty.getNumberFormatProperty() != null) {
            return NumberUtils.format(cellData.getNumberValue(), contentProperty);
        } else {
            boolean hasDataFormatData = cellData.getDataFormatData() != null
                        && cellData.getDataFormatData().getIndex() != null
                        && !StringUtils.isEmpty(cellData.getDataFormatData().getFormat());
            return hasDataFormatData
                    ? NumberDataFormatterUtils.format(
                            cellData.getNumberValue(),
                            cellData.getDataFormatData().getIndex(),
                            getFormat(cellData.getDataFormatData().getFormat()),
                            globalConfiguration)
                    : NumberUtils.format(cellData.getNumberValue(), contentProperty);
        }
    }

    public WriteCellData<?> convertToExcelData(
            String value,
            ExcelContentProperty contentProperty,
            GlobalConfiguration globalConfiguration) {
        return new WriteCellData<>(new BigDecimal(value));
    }

    private String getFormat(String format) {
        String result = "";
        if (format.contains("yyyy")) {
            result += "yyyy-MM-dd";
        } else {
            return format;
        }
        if (format.contains("h")) {
            result += " HH:mm:ss";
        }

        return result;
    }
}
